//
//  UILoginViewController.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/7/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UILoginViewController.h"

#import "UICodeVerifyViewCtrl.h"
#import "StatusBarColorManager.h"
#import "UserRegWaitViewCtrl.h"
#import "RegViewController.h"
@interface UILoginViewController ()

@end

@implementation UILoginViewController {
  UILabel* _lblLoginTips;
  UIButton* _btnForgetPswdTips;
  
  UILabel* _lblEmailBoxTip;
  UITextField* _txtEmailBox;
  
  UILabel* _lblPasswordTip;
  UITextField* _txtUserPswd;
    
  UIButton* _btnLoginLocal;
  UIButton* _btnLoginFacebook;
  //UIButton* _btnCancelLogin;
  
  UIActivityIndicatorView* _actView;
    
  UIButton* _btnRegUser;
    
  NSMutableData* _respRecvData;
  NSDateFormatter* _dtFmt;
    
  BOOL _bLoguot;
  
  BOOL _biPad;
  BOOL _biP6p;
  BOOL _biP5s;
  BOOL _bWider;
  
  UILabel* _lblForgetPswdTip;
  
  UILabel* _lblConnSvrTip;
  UISegmentedControl* _scSvrIpIdx;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_btnLoginLocal setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

- (void)viewDidLoad {
  [super viewDidLoad];
    // Do any additional setup after loading the view.
  //self.navigationController.delegate = self;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  //self.view.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.5];//[UIColor blackColor];
  CGRect frame = [[UIScreen mainScreen] bounds];
  float fScale = [UIScreen mainScreen].scale;
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  
  BOOL bIph4 = fScale == 1.0;
  
  _biPad = H > 1000;
  _biP6p = fScale >= 3.0;
  _biP5s = H >= 568 && W == 320;
  _bWider = W > 320;
  
  //UIImage* imgback = [pApp getImageScale:(_biPadDev?@"ic-Launch@1024.png":@"ic-launch3.png") scale:(_biPadDev?1.0:0.32)];//[UIImage imageNamed:@"ic-Launch@1024.png"];
  //UIImage* imgback = [pApp getImageScale:@"ic-launch1.png"  scale:(_biPad? 1.0:_biP6p? 1.0: 0.64)];
    UIImage* imgback = [pApp getImageScale:@"ic-reg2.png"  scale:(_biPad? 1.00:_biP6p? 0.5: 0.40)];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
    
    CGFloat xPos = _biPad? 120:20;
    CGFloat yPos = 80;
    _lblLoginTips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos - 1, W - xPos*2, 30)];
    _lblLoginTips.font = Bold(16);
    _lblLoginTips.textColor = [UIColor whiteColor];
    _lblLoginTips.textAlignment = NSTextAlignmentCenter;
    _lblLoginTips.text = NSLocalizedString(@"LOGIN", nil);
    [self.view addSubview:_lblLoginTips];
    
    //forget pswd
    //xPos += W/3.0 + (_biPad? -20: (_bWider?20:5));
  xPos += 30;
    _btnForgetPswdTips = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnForgetPswdTips.frame = CGRectMake(xPos, H*0.43, W-xPos*2, 30);
    //[_btnAlreadyUser setImageEdgeInsets:UIEdgeInsetsMake(-4.0, -8, 0.0, 0.0)];
    [_btnForgetPswdTips setTitle:NSLocalizedString(@"ForgotYourPswd",nil) forState:UIControlStateNormal];
    _btnForgetPswdTips.titleLabel.font = Regular(16);
    //_btnAlreadyUser.backgroundColor = [UIColor lightGrayColor];
    //_btnRegTag.layer.masksToBounds = YES;
    //_btnAlreadyUser.layer.cornerRadius = 4;
    [_btnForgetPswdTips setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnForgetPswdTips addTarget:self action:@selector(onForgetPswd:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnForgetPswdTips];
  
    [self initViewCtrls:W hgt:H];
  
  xPos = _biPad? 120:20;
  yPos = _biPad? H / 4.2: bIph4? H / 2.5: H / 3.0;
  _lblConnSvrTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, W * (_biPad?1.25:2)/5.0, 30)];
  _lblConnSvrTip.font = [UIFont systemFontOfSize: _biPad? 18.0: 13.0];
  _lblConnSvrTip.textColor = [UIColor whiteColor];
  _lblConnSvrTip.textAlignment = NSTextAlignmentLeft;
  _lblConnSvrTip.text = @"Login SVR. Address:";
  [self.view addSubview:_lblConnSvrTip];
  _lblConnSvrTip.hidden = YES;
  
  //xPos += W * (_biPadDev?1.25:2)/4.8;
  xPos += _biPad?160:20;
  yPos += 60;
  CGFloat fWidth = W - 2 * xPos;
  _scSvrIpIdx = [[UISegmentedControl alloc] initWithItems:@[@"Americas", @"International"]];
  _scSvrIpIdx.frame = CGRectMake(xPos, yPos, fWidth, 28);
  //[_scSvrIpIdx addTarget:self action:@selector(onSvrIpIdxChged:) forControlEvents:UIControlEventValueChanged];
  Byte nIdx = pApp.m_bodyInfo.nSvrIpIdx;
  _scSvrIpIdx.selectedSegmentIndex = nIdx;
  [self.view addSubview:_scSvrIpIdx];
  _scSvrIpIdx.selectedSegmentIndex = 1;
  _scSvrIpIdx.hidden = YES;
  
  /*Byte nIdx = pApp.m_bodyInfo.nSvrIpIdx;
  NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  nIdx = [userSetting integerForKey:kReg_BodySvrIdx];
  _scSvrIpIdx.selectedSegmentIndex =  pApp.m_bodyInfo.nSvrIpIdx;*/
  
  xPos = 10;//_biPadDev? 240:180;
  yPos += 160;
  _btnLoginLocal = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnLoginLocal.frame = CGRectMake(xPos, H - (H / 16.7) - 20, W-20, H / 16.7);
  //[_btnLoginLocal setBackgroundImage:[UIImage imageNamed:@"buttons_login.png"] forState:UIControlStateNormal];
  _btnLoginLocal.layer.cornerRadius = 8;
  _btnLoginLocal.tintColor = [UIColor whiteColor];
  _btnLoginLocal.backgroundColor = [UIColor colorWithRed:161.0/255 green:202.0/255 blue:64.0/255 alpha:1.0];
  [_btnLoginLocal setTitle:NSLocalizedString(@"LOGIN", nil) forState:UIControlStateNormal];
  [_btnLoginLocal addTarget:self action:@selector(onLoginSubmit:) forControlEvents:UIControlEventTouchUpInside];
    _btnLoginLocal.titleLabel.font = Regular(16);
  [self.view addSubview:_btnLoginLocal];
    
  //if(_bLoguot) {
  //xPos += 150;
  yPos += 60;
  _btnRegUser = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnRegUser.frame = CGRectMake(xPos, yPos, 260, 30);
  //[_btnRegUser setTitle:@"Create an account" forState:UIControlStateNormal];
  //[_btnRegUser setBackgroundImage:[UIImage imageNamed:@"buttons_create.png"] forState:UIControlStateNormal];

  
  _btnRegUser.titleLabel.font = [UIFont systemFontOfSize:_biPad?20:16];
  [_btnRegUser addTarget:self action:@selector(onLoginSubmit:) forControlEvents:UIControlEventTouchUpInside];
  [_btnRegUser setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
  [self.view addSubview:_btnRegUser];
  _btnRegUser.hidden = YES;
  //}
  
  //yPos += 70;
  /*_btnCancelLogin = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnCancelLogin.frame = CGRectMake(xPos, yPos, 260, 30);
  [_btnCancelLogin setTitle:@"Cancel Login" forState:UIControlStateNormal];
  //[_btnCancelLogin setBackgroundImage:[UIImage imageNamed:@"buttons_create.png"] forState:UIControlStateNormal];
  _btnCancelLogin.titleLabel.font = [UIFont systemFontOfSize:_biPad?20:16];
  [_btnCancelLogin addTarget:self action:@selector(onLoginSubmit:) forControlEvents:UIControlEventTouchUpInside];
  [_btnCancelLogin setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
  [self.view addSubview:_btnCancelLogin];*/
  
  xPos -= 150;
  yPos += 70;
  _btnLoginFacebook = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnLoginFacebook.frame = CGRectMake(xPos, yPos, 180, 40);
  [_btnLoginFacebook setBackgroundImage:[UIImage imageNamed:@"btn-fblogin.png"] forState:UIControlStateNormal];
  [_btnLoginFacebook addTarget:self action:@selector(onLoginSubmit:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnLoginFacebook];
  _btnLoginFacebook.hidden = YES;
  
  _dtFmt = pApp.dtFmt;
  _actView = nil;
  
  //forget password tips
  //xPos = 20;
  //yPos -= 50;
  CGRect rt = _btnLoginLocal.frame;
  rt.origin.y -= 28;
  rt.origin.x = xPos;
  rt.size.width = W - xPos * 2;
  _lblForgetPswdTip = [[UILabel alloc] initWithFrame:rt];
  //_lblForgetPswdTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, W - xPos*2, 30)];
  _lblForgetPswdTip.font = [UIFont systemFontOfSize: _biPad? 18.0: 14.0];
  _lblForgetPswdTip.textColor = [UIColor whiteColor];
  _lblForgetPswdTip.textAlignment = NSTextAlignmentLeft;
  //_lblForgetPswdTip.text = @"A verification code has been send to the provided e-mail address. Please enter the verification code below";
  _lblForgetPswdTip.lineBreakMode = NSLineBreakByWordWrapping;
  _lblForgetPswdTip.numberOfLines = 0;

  [self.view addSubview:_lblForgetPswdTip];
  
//  [[StatusBarColorManager sharedStatusBarColorManager] setWindowColor:[UIColor blackColor]];
//  self.navigationController.navigationBar.backgroundColor = [UIColor grayColor];
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
    [btnBack addTarget:self action:@selector(onLeftButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = btniBack;
//  UIImage* iNav = [pApp getImageScale:@"ic-accuro-n.png" scale:0.75];
//  UIImageView *imgView = [[UIImageView alloc] initWithImage:iNav];
//  imgView.contentMode = UIViewContentModeScaleAspectFit;
//  self.navigationItem.titleView = imgView;
}

-(void)onLeftButton {
    NSArray *arr = self.navigationController.viewControllers;
    
    for (id vc in arr) {
        if ([vc isKindOfClass:[UserRegWaitViewCtrl class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    UserRegWaitViewCtrl *user = [[UserRegWaitViewCtrl alloc] init];
//    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
//    [UIApplication sharedApplication].keyWindow.rootViewController = user;
    //window.rootViewController = [[UINavigationController alloc] initWithRootViewController:user];
    
    [self.navigationController pushViewController:user
                                         animated:YES];
}

- (void) navigationController:(UINavigationController*) navigationController willShowViewController:(nonnull UIViewController *)viewController animated:(BOOL)animated
{
  BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
  [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void) initViewCtrls:(CGFloat) W hgt:(CGFloat)H {
  BOOL bIpad = H > 1000;
  BOOL bWider = W > 320;
  BOOL bHigt = H > 480;
  
  CGFloat xPos = bIpad? 120: 15;
  CGFloat yPos = bIpad? 125: (bHigt? 95: 85);//bWider?120:100;
  CGFloat fWid = W - xPos * 2;
  CGFloat fHgt = H / 16.7;
  CGFloat fDelta = bIpad?50: (bHigt?30: 24);
    
    //email
    int disH = 5;
  _lblEmailBoxTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, 127, fWid, 20)];
  _lblEmailBoxTip.textColor = [UIColor whiteColor];
  _lblEmailBoxTip.font = Regular(16);
  _lblEmailBoxTip.text = @"Email";
  [self.view addSubview: _lblEmailBoxTip];
  
  yPos += 26;
    _txtEmailBox = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblEmailBoxTip.frame) + disH, fWid, fHgt)];
    _txtEmailBox.textColor = [UIColor whiteColor];
    _txtEmailBox.backgroundColor = [UIColor clearColor];
    _txtEmailBox.font = [UIFont systemFontOfSize:bIpad?20:(bWider?18:16)];
    _txtEmailBox.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtEmailBox.layer.cornerRadius = 6.0f;
  _txtEmailBox.layer.borderWidth = 1.0f;
  _txtEmailBox.layer.borderColor = [UIColor whiteColor].CGColor;
  
    //_txtName.autocapitalizationType = UITextAutocapitalizationTypeNone;
    //[_txtName addTarget:self action:@selector(textNamedDidChange:) forControlEvents:UIControlEventEditingChanged];
    _txtEmailBox.keyboardType = UIKeyboardTypeEmailAddress;
    _txtEmailBox.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _txtEmailBox.placeholder = @"";//@"Username (E-mail address)"; //NSLocalizedString(@"Name", nil);
    [self.view addSubview: _txtEmailBox];
    
    //password
    yPos += fDelta;
  _lblPasswordTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtEmailBox.frame) + disH, fWid, 20)];
  _lblPasswordTip.textColor = [UIColor whiteColor];
  _lblPasswordTip.font = Regular(16);
  _lblPasswordTip.text = NSLocalizedString(@"Password", nil);
  [self.view addSubview: _lblPasswordTip];
  
  yPos += 26;
  
    _txtUserPswd = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblPasswordTip.frame) + disH, fWid, fHgt)];
    _txtUserPswd.textColor = [UIColor whiteColor];
    _txtUserPswd.backgroundColor = [UIColor clearColor];
    _txtUserPswd.font = [UIFont systemFontOfSize:bIpad?20:(bWider?18:16)];
    _txtUserPswd.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtUserPswd.layer.cornerRadius = 6.0f;
  _txtUserPswd.layer.borderWidth = 1.0f;
  _txtUserPswd.layer.borderColor = [UIColor whiteColor].CGColor;
  
    _txtUserPswd.secureTextEntry = YES;
    _txtUserPswd.placeholder = @"";//@"Password"; //NSLocalizedString(@"Name", nil);
    [self.view addSubview: _txtUserPswd];
  _btnForgetPswdTips.frame = CGRectMake(xPos, CGRectGetMaxY(_txtUserPswd.frame) + 14, W-xPos*2, 30);
  //UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
  
  //AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//  UIImage* iLeft = [pApp getImageScale:@"btn-left-w.png" scale:0.35];
//  [btnBack setImage:iLeft forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnRegWait:) forControlEvents:UIControlEventTouchUpInside];
//  
//  //UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRedo target:self action:@selector(onRtnRegWait:)];
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
  
  self.navigationItem.rightBarButtonItem = nil;
}

/*- (void) viewDidLayoutSubviews
{
  CGFloat fScale = [UIScreen mainScreen].scale;
  if(fScale < 3.0) {
    [super viewDidLayoutSubviews];
    return;
  }
  CGFloat fHgtDelta = 4;
  CGRect frame = self.navigationController.navigationBar.frame;
  frame.size.height -= fHgtDelta;
  [self.navigationController.navigationBar setFrame:frame];
}*/

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblLoginTips.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

- (void) onSvrIpIdxChged:(id)sender
{
  //_lblLoginTips.text = @"Svr chged";
  NSInteger nIdx = _scSvrIpIdx.selectedSegmentIndex;
  NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  [userSetting setInteger:nIdx forKey:kReg_BodySvrIdx];
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //pApp.m_bodyInfo.nSvrIpIdx = nIdx;
  [pApp updSvrIpAddress:(short)nIdx];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) startTipAnimating:(id)sender
{
  _lblForgetPswdTip.text = @"";
  if(_actView == nil)
    [self actViewCreate];
  
  _txtUserPswd.hidden = YES;
  _btnLoginLocal.hidden = YES;

  _actView.hidden = NO;
  [_actView startAnimating];
  
}

- (void) stopTipAnimating:(id)sender
{
  [_actView stopAnimating];
  _actView.hidden = YES;
  
  _txtUserPswd.hidden = NO;
  _btnLoginLocal.hidden = NO;
}

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
  /*BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:checkString];*/
  
  if(checkString.length < 6) {
    return NO;
  }
  BOOL bOK = [checkString rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;
  return bOK;
}

- (void) onForgetPswd:(id)sender
{
  /*NSString* sEmail = _txtEmailBox.text;
  [self performSelectorOnMainThread:@selector(startTipAnimating:) withObject:self waitUntilDone:YES];
  
  if([_txtEmailBox isFirstResponder])
    [_txtEmailBox resignFirstResponder];
  else if([_txtUserPswd isFirstResponder])
    [_txtUserPswd resignFirstResponder];
  
  if(![self NSStringIsValidEmail:sEmail]) {
    [_btnForgetPswdTips setTitle:@"Send Me Email" forState:UIControlStateNormal];
    _lblForgetPswdTip.text = @"Please input valid E-mail address";
    
    [self performSelectorOnMainThread:@selector(stopTipAnimating:) withObject:self waitUntilDone:YES];
    _txtUserPswd.hidden = YES;
    _btnLoginLocal.hidden = YES;
    
    [_txtEmailBox becomeFirstResponder];
    return;
  }
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSDictionary *mailInfo = @{
                             @"BodyId" : @"0",
                             @"Email" : sEmail
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:@"Host/0" data:mailInfo];
  
  
  // 6.发送请求
  //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data == nil || connectionError)
      return;
    
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    sRecv = [sRecv substringFromIndex:1];
    [_btnForgetPswdTips setTitle:@"Forget your password?" forState:UIControlStateNormal];
    [self performSelectorOnMainThread:@selector(stopTipAnimating:) withObject:self waitUntilDone:YES];
    
    if([sRecv hasPrefix:NSLocalizedString(@"OK", nil)]) {
      _lblForgetPswdTip.text = @"Your password has sent to your email box, please check.";
      _btnLoginLocal.hidden = NO;
      CGPoint pt = _txtUserPswd.center;
      pt.y += 120;
      _lblForgetPswdTip.center = pt;
      AudioServicesPlaySystemSound(1109);
    }
    else {
      _txtUserPswd.hidden = YES;
      _btnLoginLocal.hidden = YES;
      AudioService.
   sPlaySystemSound(1112);
    }
    
  }];*/
  
  //_lblForgetPswdTip.text = @"";
  
  UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
  
  // When style is set to UIAlertActionStyleDestructive, the button appears with red text
  UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"Send PSWD To My Email Box" style:UIAlertActionStyleDestructive
                                handler:^(UIAlertAction * action) {
                                  NSString* sEmail = _txtEmailBox.text;
            
                                  [self performSelectorOnMainThread:@selector(startTipAnimating:) withObject:self waitUntilDone:YES];
                                  //dispatch_async(dispatch_get_main_queue(), ^(void) {
                                    //[self startTipAnimating:self];
                                  //});
   
                                  if([_txtEmailBox isFirstResponder])
                                    [_txtEmailBox resignFirstResponder];
                                  else if([_txtUserPswd isFirstResponder])
                                    [_txtUserPswd resignFirstResponder];
   
                                  if(![self NSStringIsValidEmail:sEmail]) {
                                    //_btnRegUser.hidden = YES;
                                    [_btnForgetPswdTips setTitle:@"Send Me Email" forState:UIControlStateNormal];
                                    _lblForgetPswdTip.text = @"Please input valid E-mail address";
                                    _lblForgetPswdTip.textColor = [UIColor redColor];
   
                                    [self performSelectorOnMainThread:@selector(stopTipAnimating:) withObject:self waitUntilDone:YES];
                                    _txtUserPswd.hidden = YES;
                                    _btnLoginLocal.hidden = YES;
                                    
                                    [_txtEmailBox becomeFirstResponder];
                                    AudioServicesPlaySystemSound(1112);
                                    return;
                                  }
                
                                  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                  NSDictionary *mailInfo = @{
                                                            @"BodyId" : @"0",
                                                            @"Email" : sEmail
                                                            };
                                  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:@"Host/0" data:mailInfo];
                                  
                                  
                                  // 6.发送请求
                                  //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
                                  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                    if (data == nil || connectionError)
                                      return;
                                    
                                    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                                    sRecv = [sRecv substringFromIndex:1];
                                    [_btnForgetPswdTips setTitle:NSLocalizedString(@"ForgotYourPswd",nil) forState:UIControlStateNormal];
                                    [self performSelectorOnMainThread:@selector(stopTipAnimating:) withObject:self waitUntilDone:YES];
                                    
                                    if([sRecv hasPrefix:NSLocalizedString(@"OK", nil)]) {
                                      _lblForgetPswdTip.text = @"Password has sent to your email box.";
                                      _btnLoginLocal.hidden = NO;
                                      CGPoint pt = _btnLoginFacebook.center;
                                      
                                      CGRect frame = [[UIScreen mainScreen] bounds];
                                      pt.x =  frame.size.width / 2;
                                      
                                      _lblForgetPswdTip.center = pt;
                                      AudioServicesPlaySystemSound(1109);
                                    }
                                    else if([sRecv hasPrefix:@"ActCode"]) {
                                      //tips to input verficaton code
                                       //_lblForgetPswdTip.text = @"Verfication Code and Password has sent to your email box.";
                                      NSArray *listItems = [sRecv componentsSeparatedByString:@":"];
                                      if(listItems.count > 1) {
                                        AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                        NSInteger nBodyId = ((NSString*)listItems[1]).integerValue;
                                        NSString* sEmail = _txtEmailBox.text;
                                        NSString* sFirst = nil;
                                        NSString* sLast = nil;
                                        NSString* sTagId = @"*";

                                        //pApp.m_bodyInfo.m_nBodyId = nBodyId;
                                        [pApp saveRegBodyInfo:(int)-1 email:sEmail first:sFirst last:sLast tagId:sTagId];
                                        pApp.m_nLoginBodyId = nBodyId;
                                      
                                        //popup act code NSArray nBodyId
                                        UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                                        UICodeVerifyViewCtrl * vcCodeVerify = [mainStory instantiateViewControllerWithIdentifier:@"codeVerifyViewCtrl"];
                                        [pApp.m_pNavController pushViewController:vcCodeVerify animated:YES];
                                      }
                                      
                                      _btnLoginLocal.hidden = NO;
                                      CGPoint pt = _btnLoginFacebook.center;
                                      
                                      CGRect frame = [[UIScreen mainScreen] bounds];
                                      pt.x =  frame.size.width / 2;
                                    }
                                    else {
                                      if([sRecv hasPrefix:@"Failed"]) {
                                        _lblForgetPswdTip.text = @"No such email box, please try again!";
                                      }
                                      _txtUserPswd.hidden = YES;
                                      _btnLoginLocal.hidden = YES;
                                      AudioServicesPlaySystemSound(1112);
                                    }
    
                                  }];
                                  
                                   
                                }];
  UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Try Again" style:UIAlertActionStyleCancel
                                handler:^(UIAlertAction * action) {
                                  [_btnForgetPswdTips setTitle:NSLocalizedString(@"ForgotYourPswd",nil) forState:UIControlStateNormal];
                                  _txtUserPswd.hidden = NO;
                                  _btnLoginLocal.hidden = NO;
                                  _lblForgetPswdTip.text = @"";
                                }];
  
  [alert addAction:deleteAction];
  [alert addAction:cancelAction];

  
  [self presentViewController:alert animated:NO completion:nil];
}

- (void) onLoginSubmit:(id)sender
{
#if 0
    RegViewController *reg = [[RegViewController alloc] init];
    [self.navigationController pushViewController:reg animated:YES];
    return;
#endif
    //_lblLoginTips.text = @"Login in submit";
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //[pApp.m_pNavController popViewControllerAnimated:NO];
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(sender == _btnRegUser) {
    [pApp enterPageWithRes:@"userRegViewCtrl"];
    return;
  }
  /*else if(sender == _btnCancelLogin) {
    UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController * vCtrl = [mainStory instantiateViewControllerWithIdentifier:@"userRegWaitVC"];
    [pApp.m_pNavController pushViewController:vCtrl animated:YES];
    return;
  }*/
  NSString* sEmail = _txtEmailBox.text;
  NSString* sPswd = _txtUserPswd.text;
  if(sEmail.length == 0 || sPswd.length == 0) {
    _lblLoginTips.text = @"Email & Pswd not Empty!";
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  NSInteger nIdx = _scSvrIpIdx.selectedSegmentIndex;
  NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  [userSetting setInteger:nIdx forKey:kReg_BodySvrIdx];
  [pApp updSvrIpAddress:(short)nIdx];
  
  _lblLoginTips.text = @"Waiting...";
  [self sendJsonLonginData:sEmail pswd:sPswd];
}

- (void) actViewCreate
{
  CGRect rt = _btnLoginLocal.frame;
  rt.origin.x += rt.size.width - rt.size.height * 2;
  rt.size.width = rt.size.height;
  _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
  _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
  _actView.hidesWhenStopped = YES;
  [self.view addSubview:_actView];
}

- (void) sendJsonLonginData:(NSString*) sEmail pswd:(NSString*)sPswd
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(_actView == nil) {
    [self actViewCreate];
  }
  _btnLoginLocal.hidden = YES;
  [_actView startAnimating];

  // 4.设置请求体（请求参数）
  // 创建一个描述订单信息的JSON数据
  /*NSDictionary *loginInfo = @{
                                @"BodyId" : @"-1",
                                @"Email" : sEmail,
                                @"Password" : sPswd
                                };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Mob" data:loginInfo];*/
  NSString* sUrl = [NSString stringWithFormat:@"Mob/GetMobLoginInfo/?sEmail=%@&sPswd=%@", sEmail, sPswd];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"GET" url:sUrl data:nil];

    
    // 6.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
      //debug
      /*if (data != nil || connectionError) {
        NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        AudioServicesPlaySystemSound(1112);
        return;
      }*/
      
      BOOL bNetIssue = data == nil;
      if(!bNetIssue)
        bNetIssue = data.length < 10;
      if(bNetIssue) {
        [_actView stopAnimating];
        _btnLoginLocal.hidden = NO;
        _lblLoginTips.text = @"Login failed!";//check your WAN connection and try again.;
        AudioServicesPlaySystemSound(1112);
        return;
      }
      
      NSError *e = nil;
      NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e]; //
      // NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
      if(jsonArray == nil) {
        [_actView stopAnimating];
        _btnLoginLocal.hidden = NO;
        _lblLoginTips.text = @"Login failed!";//try again.;
        AudioServicesPlaySystemSound(1112);
        return;
      }
      
      /*NSString *sBodyId = nil, *sFirstName = nil, *sLastName = nil, *sTagId = nil;;
      for(NSDictionary *item in jsonArray) {
        sBodyId = [item objectForKey:@"_nBodyId"];
        sFirstName = [item objectForKey:@"_sFirstNe"];
        sLastName = [item objectForKey:@"_sLastNe"];
        sTagId = [item objectForKey:@"_sTagId"];
      }
      
      if(sBodyId != nil) {
        [pApp saveRegBodyInfo:sBodyId.intValue email:sEmail first:sFirstName last:sLastName tagId:sTagId];
      }*/
      
      for(NSDictionary *item in jsonArray) {
        NSString* sUnitType = [item objectForKey:@"_nType"];
        int nUnitType = sUnitType.intValue;
        
        if(nUnitType < 11) {
          NSString* sTagId = [item objectForKey:@"_sTagId"];
          if([sTagId rangeOfString:@"-Err"].location != NSNotFound) {
            [_actView stopAnimating];
            _btnLoginLocal.hidden = NO;
            //_lblLoginTips.text = [NSString stringWithFormat:@"Login failed! %@", sTagId];
             _lblLoginTips.text = @"Login failed!"; //Maybe password issues.
            AudioServicesPlaySystemSound(1112);
            return;
          }
          if(sTagId.integerValue == -1) {
            _lblLoginTips.text = @"No act-code. Use right link button";
    
            [_actView stopAnimating];
            _btnLoginLocal.hidden = NO;
             AudioServicesPlaySystemSound(1112);
            return;
          }
        }
      }
      [pApp setUserLoginInfo: jsonArray email:sEmail];
      [pApp enterMainPage];
      
      [_actView stopAnimating];
      _btnLoginLocal.hidden = NO;
      
      return;
      
      
      /*NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      sRecv = [sRecv substringWithRange:NSMakeRange(1, sRecv.length-2)];
      NSArray *listItems = [sRecv componentsSeparatedByString:@":"];
      NSUInteger nCount = listItems.count;
      if(nCount > 14) {
        NSString* sBodyId = listItems[0];
        //sBodyId = [sBodyId substringWithRange: NSMakeRange(1, sBodyId.length-1)];
        NSString* sGender = listItems[1];
        NSString* sBornDate = listItems[2];
        NSString* sHgt = listItems[3];
        NSString* sHu = listItems[4];
        NSString* sTagId = listItems[5];
            
        NSString* sWgt = listItems[6];
        NSString* sWu =  listItems[7];
        NSString* sActLvl = listItems[8];
            
        NSString* sFirst = listItems[9];
        NSString* sLast = listItems[10];
        NSString* sMgr = listItems[11];
        
        //NSString* sLocId = listItems[12];
        NSString* sLocName = listItems[13];
        NSString* sLocAddr = listItems[14];
        //sLocAddr = [sLocAddr substringWithRange: NSMakeRange(0, sLocAddr.length-1)];
            
        NSDate* dtBorn = [_dtFmt dateFromString:sBornDate];
        if(dtBorn == nil) {
          [_dtFmt setDateFormat:@"MM-dd-yyyy"];
          dtBorn = [_dtFmt dateFromString:sBornDate];
        }
          
        //NSURLConnection can
        [pApp storeRegBodyInfo:sBodyId.integerValue tag:sTagId gerder:sGender.intValue born:dtBorn wgt:sWgt.floatValue wun:sWu.intValue
                           hgt:sHgt.floatValue hun:sHu.intValue lvl:sActLvl.intValue email:sEmail first:sFirst last:sLast store:[NSString stringWithFormat:@"%@(%@)", sLocName, sLocAddr]];
        
        [pApp setUserMgr:sMgr.intValue];
        
        if(nCount > 16) { //goal data
          NSString* sGoalWgt = listItems[15];
          NSString* sWgtUn = listItems[16];
          NSString * sGoalDist = @"0", *sGoalStep = @"0", *sMaxBpm = @"", *sMinBpm = @"0";
          NSString* sDistUn = [AppDelegate isLanguageChines]?@"1": @"2";
          if(nCount > 18) {
            sGoalDist = listItems[17];
            sDistUn = listItems[18];
          }
          if(nCount > 19) {
            sGoalStep = listItems[19];
          }
          
          //bpm setting
          if(nCount > 21) {
             sMaxBpm = listItems[21];
          //if(nCount > 23)
             //sMinBpm = listItems[23];
            sMinBpm = [NSString stringWithFormat:@"%.1f", sMaxBpm.floatValue / 2];
          }
    
            
          [pApp storeRegGoalData:sGoalWgt.floatValue wun:sWgtUn.intValue dist:sGoalDist.floatValue dun:sDistUn.intValue step:sGoalStep.integerValue
                          maxBpm:sMaxBpm.intValue minBpm:sMinBpm.intValue];
        }
        
        [pApp enterMainPage];
        
      }
      else {
        _lblLoginTips.text = @"Login failed!";
      }*/
        
      //_lblLoginTips.text = sRecv;
        
      /*NSError* pError;
      NSDictionary *dtDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&pError];
      if(dtDict == nil) {
      _lblLoginTips.text = @"Data exception!";
        return;
      }

      NSString* sBodyId = dtDict[@"BodyInfoId"];
      if (sBodyId.intValue <= 0) {
        _lblLoginTips.text = @"Still Not Register!";
        //[MBProgressHUD showError:error];
      } else {
      NSString* sGender =  dtDict[@"Gender"];
      NSString* sUserId = dtDict[@"UserId"];
      NSString* sTagId = dtDict[@"TagId"];
      NSString* sLast = dtDict[@"First"];
            
      //NSString *success = dtDict[@"success"];
      _lblLoginTips.text = [NSString stringWithFormat:@"%@, %@, %@, %@", sBodyId, sGender, sTagId, sLast];
      _lblLoginTips.textColor = [UIColor whiteColor];
      //[MBProgressHUD showSuccess:success];
      }*/
    }];
}

/*- (NSString*) getLoginStringData:(NSString*) sData
{
    NSRange rng = [sData rangeOfString:@"="];
    sData = [sData substringFromIndex:rng.location+1];
    return sData;
}*/

#pragma mark NSURLConnection Delegate Methods
/*- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _respRecvData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_respRecvData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection 
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{    
    if([_txtEmailBox isFirstResponder])
        [_txtEmailBox resignFirstResponder];
    else if([_txtUserPswd isFirstResponder])
        [_txtUserPswd resignFirstResponder];
}*/

- (void) onRtnRegWait:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp enterPageWithRes:@"userRegWaitVC"];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    if([_txtEmailBox isFirstResponder])
        [_txtEmailBox resignFirstResponder];
    else if([_txtUserPswd isFirstResponder])
        [_txtUserPswd resignFirstResponder];    
}

@end
